<template>
	<div>
		<div v-show="!showDetail" class="game-container report-container">
			<div class="view-container dealer-container">
				<div class="params">
					<el-form ref="form" :inline="true" :model="queryData">
						<el-form-item label="结算时间:" prop="registerTime">
							<el-date-picker
								v-model="searchTime"
								size="medium"
								:picker-options="pickerOptions"
								format="yyyy-MM-dd HH:mm:ss"
								type="datetimerange"
								range-separator="-"
								:start-placeholder="$t('common.start_date')"
								:end-placeholder="$t('common.end_date')"
								align="right"
								:clearable="false"
								:default-time="defaultTime"
								style="width: 375px"
								class="time-options-value"
							></el-date-picker>
						</el-form-item>

						<el-form-item label="总代账号:" prop="proxyName">
							<el-input
								v-model="queryData.proxyName"
								size="medium"
								placeholder="请输入代理账号"
								clearable
								style="width: 180px"
								maxlength="11"
							></el-input>
						</el-form-item>
						<el-form-item label="下注会员账号:" prop="memberName">
							<el-input
								v-model="queryData.memberName"
								size="medium"
								placeholder="请输入代理账号"
								clearable
								style="width: 180px"
								maxlength="11"
							></el-input>
						</el-form-item>
						<el-form-item
							label="会员所属代理:"
							prop="parentProxyName"
						>
							<el-input
								v-model="queryData.parentProxyName"
								size="medium"
								placeholder="请输入代理账号"
								clearable
								style="width: 180px"
								maxlength="11"
							></el-input>
						</el-form-item>
						<el-form-item label="总代输赢:">
							<el-select
								v-model="queryData.proxyWinOrLose"
								size="medium"
								:placeholder="$t('common.select_all')"
								clearable
								style="width: 180px"
							>
								<el-option
									v-for="item in proxyWinOrLoseArr"
									:key="item.code"
									:label="item.description"
									:value="item.code"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="总代盈亏:">
							<el-input-number
								v-model="queryData.proxyWinOrLoseAmountMin"
								size="medium"
								:placeholder="$t('common.minimum')"
								style="width: 130px"
								:min="-9999999999"
								:max="9999999999"
								:controls="false"
								name="proxyWinOrLoseAmountMin"
								@blur="checkValue($event)"
							></el-input-number>
							-
							<el-input-number
								v-model="queryData.proxyWinOrLoseAmountMax"
								size="medium"
								:placeholder="$t('common.maximum')"
								style="width: 130px"
								:min="-9999999999"
								:max="9999999999"
								:controls="false"
								name="proxyWinOrLoseAmountMax"
								@blur="checkValue($event)"
							></el-input-number>
						</el-form-item>
						<el-form-item label="平台利润:">
							<el-input-number
								v-model="queryData.venueCommissionAmountMin"
								size="medium"
								:placeholder="$t('common.minimum')"
								style="width: 130px"
								:min="-9999999999"
								:max="9999999999"
								:controls="false"
								name="venueCommissionAmountMin"
								@blur="checkValue($event)"
							></el-input-number>
							-
							<el-input-number
								v-model="queryData.venueCommissionAmountMax"
								size="medium"
								:placeholder="$t('common.maximum')"
								style="width: 130px"
								:min="-9999999999"
								:max="9999999999"
								:controls="false"
								name="venueCommissionAmountMax"
								@blur="checkValue($event)"
							></el-input-number>
						</el-form-item>
						<el-form-item label="注单号:" prop="id">
							<el-input
								v-model="queryData.id"
								size="medium"
								placeholder="请输入代理账号"
								clearable
								style="width: 300px"
							></el-input>
						</el-form-item>
						<el-form-item label="三方订单号:" prop="thirdOrderId">
							<el-input
								v-model="queryData.thirdOrderId"
								size="medium"
								placeholder="请输入代理账号"
								clearable
								style="width: 300px"
							></el-input>
						</el-form-item>
						<el-form-item label="游戏平台:">
							<el-select
								v-model="queryData.gameCode"
								size="medium"
								:placeholder="$t('common.select_all')"
								clearable
								multiple
								collapse-tags
								style="width: 260px"
							>
								<el-option
									v-for="item in gameTypeList"
									:key="item.gameCode"
									:label="item.gameName"
									:value="item.gameCode"
								></el-option>
							</el-select>
						</el-form-item>

						<el-form-item>
							<el-button
								type="primary"
								icon="el-icon-search"
								size="medium"
								@click="search"
							>
								查询
							</el-button>
							<el-button
								icon="el-icon-refresh-left"
								size="medium"
								@click="reset"
							>
								重置
							</el-button>
							<el-button
								v-if="hasPermission('1030522')"
								type="warning"
								icon="el-icon-folder-add"
								size="medium"
								:disabled="loading"
								@click="exportExcel"
							>
								导出
							</el-button>
						</el-form-item>
					</el-form>
				</div>

				<div class="content">
					<el-table
						v-loading="loading"
						element-loading-spinner="el-icon-loading"
						border
						class="small-size-table"
						show-summary
						:summary-method="getSummaries"
						:header-cell-style="getRowClass"
						:data="dataList"
						@sort-change="_changeTableSort"
					>
						<el-table-column
							prop="auditStep"
							align="center"
							:label="$t('common.actions')"
							width="120"
						>
							<template slot-scope="scope">
								<el-button
									type="primary"
									size="medium"
									@click="openDetail(scope.row)"
								>
									查看详情
								</el-button>
							</template>
						</el-table-column>
						<el-table-column
							label="注单号"
							prop="注单号"
							align="center"
						>
							<template slot="header">
								注单号
								<br />
								三方订单号
							</template>
							<template slot-scope="scope">
								<span>
									{{ scope.row.id || '-' }}
								</span>
								<br />
								<span>
									{{ scope.row.thirdOrderId || '-' }}
								</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="netAt"
							align="center"
							label="结算时间"
						>
							<template slot-scope="scope">
								{{ scope.row.netAt }}
							</template>
						</el-table-column>
						<el-table-column
							prop="gameCode"
							align="center"
							label="游戏平台"
						>
							<template slot-scope="scope">
								{{ filterGameType(scope.row.gameCode) }}
							</template>
						</el-table-column>
						<el-table-column
							prop="proxyName"
							align="center"
							:label="$t('funds.fund_audit.top_proxy_name')"
						>
							<template slot-scope="scope">
								{{ scope.row.proxyName || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							prop="memberName"
							align="center"
							label="下注会员账号"
						>
							<template slot-scope="scope">
								{{ scope.row.memberName || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							prop="parentProxyName"
							align="center"
							label="会员所属代理"
						>
							<template slot-scope="scope">
								{{ scope.row.parentProxyName || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							prop="proxyWinOrLose"
							align="center"
							label="总代输赢"
						>
							<template slot-scope="scope">
								{{
									typeFilter(
										scope.row.proxyWinOrLose,
										'proxyWinOrLose'
									)
								}}
							</template>
						</el-table-column>

						<el-table-column
							sortable="custom"
							prop="proxyWinOrLoseAmount"
							align="center"
							label="总代盈亏"
						>
							<template slot-scope="scope">
								<span
									:class="
										getNumberValColor(
											scope.row.proxyWinOrLoseAmount
										)
									"
								>
									{{
										decimalToFixed2(
											scope.row.proxyWinOrLoseAmount
										)
									}}
								</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="venueCommissionRate"
							align="center"
							label="抽佣比例"
						>
							<template slot-scope="scope">
								<span
									v-if="
										scope.row.venueCommissionRate ||
											scope.row.venueCommissionRate === 0
									"
								>
									{{
										handlePercentage(
											scope.row.venueCommissionRate
										)
									}}
								</span>
								<span v-else>-</span>
							</template>
						</el-table-column>
						<el-table-column
							sortable="custom"
							prop="venueCommissionAmount"
							align="center"
							label="平台利润"
						>
							<template slot-scope="scope">
								{{
									decimalToFixed2(
										scope.row.venueCommissionAmount
									)
								}}
							</template>
						</el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination
						class="pageValue"
						:current-page.sync="pageNum"
						background
						layout="total, sizes,prev, pager, next, jumper"
						:page-size="pageSize"
						:page-sizes="pageSizes"
						:total="total"
						@current-change="handleCurrentChange"
						@size-change="handleSizeChange"
					></el-pagination>
				</div>
			</div>
		</div>
		<Details
			v-if="showDetail"
			:row-data="rowData"
			:game-type="gameType"
			@go-back="back"
		/>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
const startTime = dayjs()
	.startOf('day')
	.valueOf()
const endTime = dayjs()
	.endOf('day')
	.valueOf()
import { Decimal } from 'decimal.js'
import { routerNames } from '@/utils/consts'
import Details from './components/Details'

export default {
	name: routerNames.eatOrderComissionRecord,
	components: { Details },
	mixins: [list],
	data() {
		return {
			queryData: {},
			searchTime: [startTime, endTime],
			dataList: [],
			summary: {},
			showDetail: false,
			rowData: {},
			gameTypeList: []
		}
	},
	computed: {
		proxyWinOrLoseArr() {
			return this.globalDics.proxyWinOrLose || []
		}
	},
	created() {
		this.getGameTypeList()
	},
	methods: {
		getGameTypeList() {
			this.$api.getMerchantGameGamePlant().then((res) => {
				this.gameTypeList = res.data || []
			})
		},
		filterGameType(gameCode) {
			return (
				this.gameTypeList.find((item) => item.gameCode === gameCode)
					?.gameName || '-'
			)
		},
		back() {
			this.showDetail = false
			this.loadData()
		},
		openDetail(row) {
			this.showDetail = true
			this.rowData = Object.assign({}, row)
			this.gameType = this.filterGameType(row.gameCode)
		},
		loadData() {
			this.loading = true
			const [netAtStart, netAtEnd] = this.searchTime || []
			const params = {
				...this.getParams(this.queryData),
				netAtStart: netAtStart
					? dayjs(netAtStart).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				netAtEnd: netAtEnd
					? dayjs(netAtEnd).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			this.$api
				.eatTakeCommissionRecord(params)
				.then((res) => {
					this.dataList = res.data?.record || []
					this.total = res.data?.totalRecord || 0
					this.summary = res.data?.summary || {}
					this.loading = false
				})
				.catch(() => (this.loading = false))
		},

		getSummaries(params) {
			const { columns, data } = params
			const obj = {
				总代盈亏: '总代盈亏',
				平台利润: '平台利润'
			}
			const sums = []
			columns.forEach((column, index) => {
				if (index === 0) {
					const el = (
						<div class='count_row'>
							<p>小计</p>
							<p>合计</p>
						</div>
					)
					sums[index] = el
					return
				} else if (this.summary !== null) {
					const values = data.map((item) =>
						Number(item[column.property])
					)
					if (column.label === obj[column.label]) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr)
							if (!isNaN(value)) {
								return new Decimal(prev)
									.add(new Decimal(curr))
									.toNumber()
							} else {
								return prev
							}
						}, 0)
						const num = sums[index]
						switch (column.label) {
							case '总代盈亏':
								sums[index] = (
									<div class='count_row'>
										<p class={this.getNumberValColor(num)}>
											{this.filterSummar(num)}
										</p>
										<p
											class={this.getNumberValColor(
												this.summary
													.proxyWinOrLoseAmount
											)}
										>
											{this.filterSummar(
												this.summary
													.proxyWinOrLoseAmount
											)}
										</p>
									</div>
								)
								break
							case '平台利润':
								sums[index] = (
									<div class='count_row'>
										<p>{this.filterSummar(num)}</p>
										<p>
											{this.filterSummar(
												this.summary
													.venueCommissionAmount
											)}
										</p>
									</div>
								)
								break
						}
					} else {
						sums[index] = ''
					}
				}
			})
			return sums
		},
		reset() {
			this.queryData = {}
			this.searchTime = [startTime, endTime]
			this.$refs['form'].resetFields()
			this.search()
		},
		_changeTableSort({ column, prop, order }) {
			const obj = {
				总代盈亏: 10,
				平台利润: 12
			}
			this.queryData.orderKey = obj[column.label]
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},
		checkValue(e) {
			const { name, value } = e.target
			switch (name) {
				case 'proxyWinOrLoseAmountMin':
					if (
						value &&
						value * 1 > this.queryData.proxyWinOrLoseAmountMax * 1
					) {
						this.$message({
							type: 'warning',
							message: `总代盈亏最小值不能大于最大值`
						})
						this.queryData.proxyWinOrLoseAmountMin = undefined
					} else if (value !== '') {
						this.queryData.proxyWinOrLoseAmountMin = value
					} else {
						this.queryData.proxyWinOrLoseAmountMin = undefined
					}
					break
				case 'proxyWinOrLoseAmountMax':
					if (
						value &&
						value * 1 < this.queryData.proxyWinOrLoseAmountMin * 1
					) {
						this.$message({
							type: 'warning',
							message: `总代盈亏最大值不能小于最小值`
						})
						this.queryData.proxyWinOrLoseAmountMax = undefined
					} else if (value !== '') {
						this.queryData.proxyWinOrLoseAmountMax = value
					} else {
						this.queryData.proxyWinOrLoseAmountMax = undefined
					}
					break

				case 'venueCommissionAmountMin':
					if (
						value &&
						value * 1 > this.queryData.venueCommissionAmountMax * 1
					) {
						this.$message({
							type: 'warning',
							message: `平台分润最小值不能大于最大值`
						})
						this.queryData.venueCommissionAmountMin = undefined
					} else if (value !== '') {
						this.queryData.venueCommissionAmountMin = value
					} else {
						this.queryData.venueCommissionAmountMin = undefined
					}
					break
				case 'venueCommissionAmountMax':
					if (
						value &&
						value * 1 < this.queryData.venueCommissionAmountMin * 1
					) {
						this.$message({
							type: 'warning',
							message: `平台分润最大值不能小于最小值`
						})
						this.queryData.venueCommissionAmountMax = undefined
					} else if (value !== '') {
						this.queryData.venueCommissionAmountMax = value
					} else {
						this.queryData.venueCommissionAmountMax = undefined
					}
					break
			}
		},
		exportExcel() {
			const [netAtStart, netAtEnd] = this.searchTime || []
			const params = {
				...this.getParams(this.queryData),
				netAtStart: netAtStart
					? dayjs(netAtStart).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				netAtEnd: netAtEnd
					? dayjs(netAtEnd).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			this.$confirm(
				`<strong>${this.$t(
					'common.is_export'
				)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'common.excess_data'
				)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.$api
						.eatTakeCommissionRecordExportExcel(params)
						.then((res) => {
							const { data, status } = res
							if (res && status === 200) {
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: this.$t(
											'common.export_success'
										),
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
							this.$message({
								type: 'error',
								message: '导出失败',
								duration: 1500
							})
						})
				})
				.catch(() => {})
		}
	}
}
</script>

<style lang="scss" scoped>
// 合计样式
.count_row {
	height: 80px;
	p {
		height: 40px;
		line-height: 40px;
		font-weight: 700;
		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}
}
</style>
